package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.ClearCache;
import com.cy.pj.common.annotation.RequiredCache;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.vo.Node;
import com.cy.pj.sys.dao.SysDeptDao;
import com.cy.pj.sys.pojo.SysDept;
import com.cy.pj.sys.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysDeptServiceImpl implements SysDeptService {

	@Autowired
	private SysDeptDao sysDeptDao;

	// @RequiredCache()
	@Override
	@Cacheable(value = "deptCache")
	public List<Map<String, Object>> findObjects() {
		List<Map<String, Object>> list = sysDeptDao.findObjects();
		if (list == null || list.size() == 0) {
			throw new ServiceException("没有部门信息");
		}
		return list;
	}

	@Override
	// @ClearCache("删除数据")
	@CacheEvict(value = "deptCache",allEntries = true)
	public int deleteObject(Integer id) {
		if (id == null || id < 0) {
			throw new ServiceException("数据不合法: id=" + id);
		}
		int childCount = sysDeptDao.getChildCount(id);
		if (childCount > 0) {
			throw new ServiceException("当前部门存在子部门,请先删除当前部门下的子部门!");
		}
		// 此处和User表关联,后续有关联删除判断,暂时放置.
		// int userCount=sysUserDao.getUserCountByDeptId(id);
		// if(userCount>0){
		// throw new ServiceException("此部门有员工，不允许对部门进行删除");
		// }
		int rows = sysDeptDao.deleteObject(id);
		if (rows == 0) {
			throw new ServiceException("此部门可能已经不存在.");
		}
		return rows;
	}

	@Override
	@RequiredCache
	public List<Node> findZTreeNodes() {
		List<Node> list = sysDeptDao.findZTreeNodes();
		if (list == null || list.size() == 0) {
			throw new ServiceException("没有部门信息");
		}
		return list;
	}

	@Override
	@ClearCache("添加数据")
	public int saveObject(SysDept entity) {
		if (entity == null) {
			throw new ServiceException("保存部门对象不能为空。");
		}
		if (StringUtils.isEmpty(entity.getName())) {
			throw new ServiceException("部门名不能为空。");
		}
		int rows = sysDeptDao.insertObject(entity);
		return rows;
	}

	@Override
	@ClearCache("更新数据")
	public int updateObject(SysDept entity) {
		if (entity == null) {
			throw new ServiceException("保存对象不能为空");
		}
		if (StringUtils.isEmpty(entity.getName())) {
			throw new ServiceException("部门不能为空");
		}
		int rows;
		try {
			rows = sysDeptDao.updateObject(entity);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("更新失败");
		}
		return rows;
	}
}
